# encoding: utf-8
import os.path

import cdsapi

c = cdsapi.Client()

variable = ['temperature']

years = ['2016', '2017', '2018', '2019', '2020', '2021']

month = ['01', '02', '03', '04', '05', '06', '07', '08',
         '09', '10', '11', '12']

day = ['01', '02', '03', '04', '05', '06',
       '07', '08', '09', '10', '11', '12',
       '13', '14', '15', '16', '17', '18',
       '19', '20', '21', '22', '23', '24',
       '25', '26', '27', '28', '29', '30', '31']

time = ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
        '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
        '12:00', '13:00', '14:00', '15:00', '16:00', '17:00',
        '18:00', '19:00', '20:00', '21:00', '22:00', '23:00']

var = {
    'product_type': 'reanalysis',
    'format': 'grib',
    'variable': 'temperature',
    'pressure_level': [],
    'year': [],
    'month': month,
    'day': day,
    'time': time
}

level = [1, 2, 3, 5, 7, 10, 20, 30,
         50, 70, 100, 125, 150, 175, 200, 225,
         250, 300, 350, 400, 450, 500, 550, 600,
         650, 700, 750, 775, 800, 825, 850, 875, 900,
         925, 950, 975, 1000]  # pressure-levels

for level_index in range(4):
    var['pressure_level'] = str(level[level_index])
    for year in years:
        var['year'] = year
        save_path = f'./Temperature_6years/{level[level_index]}hPa_{year}year.grib'

        if os.path.isfile(save_path) and not os.path.isfile(f"{save_path}.aria2"):
            print(f'{save_path} exists')
        else:
            print(f"download {save_path}")
            c.retrieve(
                'reanalysis-era5-pressure-levels',
                var,
                save_path)
